package util

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"errors"
	"io"
)

var ErrAesCiphertextTooShort = errors.New(`ciphertext is too short`)
var ErrAesCiphertextWrong = errors.New(`ciphertext is not a multiple of the block size`)

// AesCBCEncrypt 加密，key 16位
func AesCBCEncrypt(str, key string) (string, error) {
	keyBytes := []byte(key)
	rawData := []byte(str)
	var block cipher.Block
	var err error
	block, err = aes.NewCipher(keyBytes)
	if err != nil {
		return "", err
	}
	blockSize := block.BlockSize()
	rawData = PKCS7Padding(rawData, blockSize)
	cipherText := make([]byte, blockSize+len(rawData))
	iv := cipherText[:blockSize]
	if _, err = io.ReadFull(rand.Reader, iv); err != nil {
		return "", err
	}
	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(cipherText[blockSize:], rawData)
	return base64.StdEncoding.EncodeToString(cipherText), nil
}

// AesCBCDecrypt 解密
func AesCBCDecrypt(str, key string) (string, error) {
	var encryptData []byte
	var err error
	encryptData, err = base64.StdEncoding.DecodeString(str)
	if err != nil {
		return "", err
	}
	keyBytes := []byte(key)
	block, err := aes.NewCipher(keyBytes)
	if err != nil {
		return "", err
	}
	blockSize := block.BlockSize()
	if len(encryptData) < blockSize {
		return "", ErrAesCiphertextTooShort
	}
	iv := encryptData[:blockSize]
	encryptData = encryptData[blockSize:]
	if len(encryptData)%blockSize != 0 {
		return "", ErrAesCiphertextWrong
	}
	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(encryptData, encryptData)
	encryptData = PKCS7UnPadding(encryptData)
	return string(encryptData), nil
}

// PKCS7Padding 补位
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	text := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, text...)
}

// PKCS7UnPadding 取消补位
func PKCS7UnPadding(origData []byte) []byte {
	length := len(origData)
	return origData[:(length - int(origData[length-1]))]
}
